import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:craze/common/index.dart';
import 'package:go_router/go_router.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:wechat_assets_picker/wechat_assets_picker.dart';
import 'package:craze/services/service_locator.dart';
import 'package:craze/stores/auth_store.dart';
import 'package:path_provider/path_provider.dart';
import 'package:path/path.dart' as path;

class EditView extends StatefulWidget {
  const EditView({super.key});

  @override
  State<EditView> createState() => _EditViewState();
}

class _EditViewState extends State<EditView> {
  final TextEditingController _nameController = TextEditingController();
  final TextEditingController _bioController = TextEditingController();
  String? _selectedAvatarPath;
  AssetEntity? _selectedAsset;
  File? _selectedImageFile;

  // 获取 auth_store 实例
  final AuthStore _authStore = getIt<AuthStore>();
  bool _isLoading = false;

  @override
  void initState() {
    super.initState();
    // 从 AuthStore 获取当前用户信息
    _loadUserData();
  }

  // 加载用户数据
  void _loadUserData() {
    final user = _authStore.currentUser;
    if (user != null) {
      setState(() {
        _nameController.text = user.name;
        _bioController.text = user.description;
      });
    }
  }

  @override
  void dispose() {
    _nameController.dispose();
    _bioController.dispose();
    super.dispose();
  }

  // Open asset picker for selecting avatar
  Future<void> _selectAvatar() async {
    final List<AssetEntity>? result = await AssetPicker.pickAssets(
      context,
      pickerConfig: AssetPickerConfig(
        maxAssets: 1,
        requestType: RequestType.image,
        themeColor: Colors.blue,
      ),
    );

    if (result != null && result.isNotEmpty) {
      final File? file = await result.first.file;
      if (file != null) {
        setState(() {
          _selectedAsset = result.first;
          _selectedImageFile = file;
        });
      }
    }
  }

  // 保存图片到本地应用目录
  Future<String?> _saveAvatarToLocal(File imageFile) async {
    try {
      // 获取应用文档目录
      final appDir = await getApplicationDocumentsDirectory();
      // 创建保存头像的子目录
      final avatarDir = Directory('${appDir.path}/avatars');
      if (!await avatarDir.exists()) {
        await avatarDir.create(recursive: true);
      }

      // 生成唯一文件名
      final fileName =
          'avatar_${DateTime.now().millisecondsSinceEpoch}${path.extension(imageFile.path)}';
      final savedImagePath = '${avatarDir.path}/$fileName';

      // 复制图片到新目录
      final newImage = await imageFile.copy(savedImagePath);

      // 返回保存的路径
      return newImage.path;
    } catch (e) {
      if (mounted) {
        MyToast.showError(context, 'Failed to save avatar: ${e.toString()}');
      }
      return null;
    }
  }

  // 保存用户资料
  Future<void> _saveProfile() async {
    if (_nameController.text.trim().isEmpty) {
      MyToast.showError(context, 'Name cannot be empty');
      return;
    }

    setState(() {
      _isLoading = true;
    });

    try {
      // 保存头像并获取本地存储路径
      String? avatarPath;

      if (_selectedImageFile != null) {
        // 显示保存中提示
        final loadingToast = MyToast.showLoading(context, 'Saving avatar...');

        // 保存图片到本地
        avatarPath = await _saveAvatarToLocal(_selectedImageFile!);

        // 关闭保存中提示
        MyToast.dismiss(loadingToast);

        if (avatarPath == null) {
          throw Exception('Failed to save avatar image');
        }
      }

      // 调用 AuthStore 的方法更新用户资料
      await _authStore.updateProfile(
        name: _nameController.text.trim(),
        description: _bioController.text.trim(),
        avatar: avatarPath, // 如果有新头像则使用本地路径，否则不更新头像
      );

      // 显示成功提示
      if (mounted) {
        MyToast.showSuccess(context, 'Profile updated successfully');

        // 返回上一页
        Future.delayed(const Duration(seconds: 1), () {
          if (mounted) {
            Navigator.of(context).pop();
          }
        });
      }
    } catch (e) {
      if (mounted) {
        MyToast.showError(context, 'Failed to update profile: ${e.toString()}');
      }
    } finally {
      if (mounted) {
        setState(() {
          _isLoading = false;
        });
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    final user = _authStore.currentUser;

    return Scaffold(
      body: Container(
        decoration: BoxDecoration(
          image: DecorationImage(
            image: AssetImage(MyImages.commonBg),
            fit: BoxFit.cover,
          ),
        ),
        child: SafeArea(
          child: Column(
            children: [
              // Header with back button and title
              Padding(
                padding: EdgeInsets.symmetric(horizontal: 20.w),
                child: Stack(
                  alignment: Alignment.center,
                  children: [
                    // Back button aligned to the left
                    Align(
                      alignment: Alignment.centerLeft,
                      child: GestureDetector(
                        onTap: () {
                          GoRouter.of(context).pop();
                        },
                        child: Icon(
                          MyIcons.iconBack,
                          color: Colors.white,
                          size: 24.sp,
                        ),
                      ),
                    ),
                    // Title centered
                    Text(
                      'Edit',
                      style: TextStyle(
                        color: Colors.white,
                        fontSize: 24.sp,
                        fontFamily: GoogleFonts.mochiyPopOne().fontFamily,
                        fontWeight: FontWeight.w400,
                      ),
                    ),
                  ],
                ),
              ),

              SizedBox(height: 20.h),

              // Avatar selection - 修改为使用整个区域作为触摸区域
              GestureDetector(
                onTap: _selectAvatar,
                child: Container(
                  width: double.infinity,
                  padding: EdgeInsets.symmetric(horizontal: 20.w),
                  child: Row(
                    children: [
                      // Avatar
                      Container(
                        width: 80.w,
                        height: 80.w,
                        decoration: BoxDecoration(
                          shape: BoxShape.circle,
                          border: Border.all(color: Colors.white, width: 2.w),
                        ),
                        child: ClipRRect(
                          borderRadius: BorderRadius.circular(40.r),
                          child:
                              _selectedAsset != null
                                  ? AssetEntityImage(
                                    _selectedAsset!,
                                    isOriginal: false,
                                    fit: BoxFit.cover,
                                  )
                                  : user?.avatar.isNotEmpty == true
                                  ? user!.avatar.startsWith('assets/')
                                      ? Image.asset(
                                        user.avatar,
                                        fit: BoxFit.cover,
                                      )
                                      : Image.file(
                                        File(user.avatar),
                                        fit: BoxFit.cover,
                                        errorBuilder: (
                                          context,
                                          error,
                                          stackTrace,
                                        ) {
                                          return Image.asset(
                                            MyImages.touxiang1,
                                            fit: BoxFit.cover,
                                          );
                                        },
                                      )
                                  : Image.asset(
                                    MyImages.touxiang1,
                                    fit: BoxFit.cover,
                                  ),
                        ),
                      ),

                      // 填充空间但保持可点击
                      Expanded(
                        child: Container(
                          alignment: Alignment.centerRight,
                          child: Container(
                            padding: EdgeInsets.all(4.r),
                            decoration: BoxDecoration(
                              color: Colors.black45,
                              shape: BoxShape.circle,
                            ),
                            child: Icon(
                              Icons.arrow_forward_ios,
                              color: Colors.white,
                              size: 16.sp,
                            ),
                          ),
                        ),
                      ),
                    ],
                  ),
                ),
              ),

              SizedBox(height: 40.h),

              // Name field
              Padding(
                padding: EdgeInsets.symmetric(horizontal: 20.w),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      'Name',
                      style: TextStyle(
                        color: Colors.grey,
                        fontSize: 14.sp,
                        fontFamily: GoogleFonts.inter().fontFamily,
                      ),
                    ),
                    TextField(
                      controller: _nameController,
                      style: TextStyle(
                        color: Colors.white,
                        fontSize: 16.sp,
                        fontFamily: GoogleFonts.inter().fontFamily,
                      ),
                      decoration: InputDecoration(
                        border: UnderlineInputBorder(
                          borderSide: BorderSide(color: Colors.grey),
                        ),
                        enabledBorder: UnderlineInputBorder(
                          borderSide: BorderSide(color: Colors.grey),
                        ),
                        focusedBorder: UnderlineInputBorder(
                          borderSide: BorderSide(color: Colors.blue),
                        ),
                      ),
                    ),
                  ],
                ),
              ),

              SizedBox(height: 30.h),

              // Bio field
              Padding(
                padding: EdgeInsets.symmetric(horizontal: 20.w),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      'Signature',
                      style: TextStyle(
                        color: Colors.grey,
                        fontSize: 14.sp,
                        fontFamily: GoogleFonts.inter().fontFamily,
                      ),
                    ),
                    TextField(
                      controller: _bioController,
                      style: TextStyle(
                        color: Colors.white,
                        fontSize: 16.sp,
                        fontFamily: GoogleFonts.inter().fontFamily,
                      ),
                      maxLines: 2,
                      decoration: InputDecoration(
                        border: UnderlineInputBorder(
                          borderSide: BorderSide(color: Colors.grey),
                        ),
                        enabledBorder: UnderlineInputBorder(
                          borderSide: BorderSide(color: Colors.grey),
                        ),
                        focusedBorder: UnderlineInputBorder(
                          borderSide: BorderSide(color: Colors.blue),
                        ),
                      ),
                    ),
                  ],
                ),
              ),

              const Spacer(),

              // Confirm button
              Padding(
                padding: EdgeInsets.symmetric(horizontal: 20.w, vertical: 20.h),
                child: Container(
                  width: double.infinity,
                  height: 50.h,
                  decoration: BoxDecoration(
                    color: Colors.blue,
                    borderRadius: BorderRadius.circular(25.r),
                  ),
                  child:
                      _isLoading
                          ? Center(
                            child: CircularProgressIndicator(
                              color: Colors.white,
                            ),
                          )
                          : TextButton(
                            onPressed: _saveProfile,
                            child: Text(
                              'Confirm',
                              style: TextStyle(
                                color: Colors.white,
                                fontSize: 18.sp,
                                fontWeight: FontWeight.w600,
                                fontFamily: GoogleFonts.inter().fontFamily,
                              ),
                            ),
                          ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}
